package com.karileet.nokia.meeting.profile;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Switch;

public class MainActivity extends Activity {
	public static final String PREFS_NAME = "MeetingProfilePrefsFile";
	public static String APP = "Meeting profile";
	public ProfileState state;
	private Switch tb;
	private Switch tv;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tb = (Switch) findViewById(R.id.toggle_profile_switch);
        tv = (Switch) findViewById(R.id.toggle_vibrate_switch);
        final MeetingProfile mp = new MeetingProfile(this);
		disableVibrateToggleWhenActive();
		tb.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				state.setProfileEnabled(tb.isChecked());
				disableVibrateToggleWhenActive();
				if (tb.isChecked()) {
					mp.enable(state);
				} else {
					mp.disable();
				}
			}
		});
		tv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				state.setVibrateEnabled(tv.isChecked());
			}
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onPause() {
    	super.onPause();
    	try {
    		SharedPreferences p = getSharedPreferences(PREFS_NAME, 0);
	    	p.edit().putBoolean("vibrate", state.isVibrateEnabled()).commit();
	    	p.edit().putBoolean("profile", state.isProfileEnabled()).commit();
    	} catch (Exception e) {
    		Log.e(APP, "Unable to pause app: " + e.getMessage());
    	}
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	SharedPreferences p = getSharedPreferences(PREFS_NAME, 0);
    	state = new ProfileState(this);
    	state.setProfileEnabled(p.getBoolean("profile", false));
    	state.setVibrateEnabled(p.getBoolean("vibrate", false));
    	tv.setChecked(state.isVibrateEnabled());
    	tb.setChecked(state.isProfileEnabled());
    	disableVibrateToggleWhenActive();
    }

	/**
	 * Method disables vibrate toggle in UI
	 */
	private void disableVibrateToggleWhenActive() {
		Log.d(APP, "Starting 'disableVibratorCbWhenActive' method");
		Switch tv = (Switch) findViewById(R.id.toggle_vibrate_switch);
		Switch tp = (Switch) findViewById(R.id.toggle_profile_switch);
		tv.setEnabled(!tp.isChecked());
	}    
}
